import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mi_mang_flutter/api/daily_words_api.dart';
import 'package:mi_mang_flutter/model/daily_word_model.dart';
import 'package:mi_mang_flutter/provider/locale_provider.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/shared_preferences.dart';
import 'package:mi_mang_flutter/manager/app_manager.dart';
import 'package:provider/provider.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  DailyWordModel? model;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // /// 预先缓存图片，避免直接使用时因为首次加载造成闪动
      // _guideList.forEach((image) {
      //   precacheImage(loadAssetImage(image), context);
      // });
      _initSystemLocale(context);
      AppManager.initApp(context).then((_) {
        print("AppManager init success");
        _initSplash();
      });
    });

    var modelMap = SpUtil.getObject(SPKeys.HOME_DAILY_KEY);
    if (modelMap != null) {
      model = DailyWordModel.fromJson(modelMap);
    }
  }

  /// 初始化语言
  /// 获取系统语言,如果app未支持该语言,则默认使用英语
  static void _initSystemLocale(BuildContext context) {
    var locale = View.of(context).platformDispatcher.locale;
    Provider.of<LocaleProvider>(context, listen: false).systemLocale(locale);
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _initAsync() {
    AppManager.pushHomePage(context);

    // // 测试首次加载动画, 将SHOWWELCOME设置默认值等于true
    // // SpUtil.putBool(SPKeys.SHOWWELCOME, true);
    // if (SpUtil.getBool(SPKeys.SHOWWELCOME, defValue: true)) {
    //   SpUtil.putBool(SPKeys.SHOWWELCOME, false);
    // } else {
    //   AppManager.pushHomePage(context);
    //   // if (Platform.isAndroid) {
    //   //   AppManager.checkUpgrade(context);
    //   // }
    //   // SpUtil.getObject(SPKeys.TOKEN_KEY) != null
    //   //     ? AppManager.goHomePage()
    //   //     : AppManager.goLogin();
    // }
  }

  void _initSplash() async {
    try {
      var response = await DailyWordsApi.getDailyWordsPage(
        pageNum: 1,
        pageSize: 1,
        connectTimeout: 3000,
      );
      var dailyModel = response.data?.records?.first;
      if (dailyModel != null) {
        SpUtil.putObject(SPKeys.HOME_DAILY_KEY, dailyModel);
        // CachedNetworkImageProvider provider =
        //     CachedNetworkImageProvider(response.data.records.first.imageUrl);
        // NetworkImage(response.data.records.first.imageUrl);
        // 预先缓存图片，避免直接使用时因为首次加载造成闪动
        var imageNetwork = Image.network(dailyModel.imageUrl!);
        await precacheImage(imageNetwork.image, context);
      }
    } catch (e) {}
    await Future.delayed(Duration(seconds: 2), _initAsync);
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: Material(
        child: model == null ? _defaultImage() : _networkImage(),
      ),
    );
  }

  Widget _defaultImage() {
    return loadImage(
      "start_page",
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.cover,
    );
  }

  Widget _networkImage() {
    return loadNetworkImage(
      model!.imageUrl,
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.cover,
    );
  }
}
